package com.zdp.security.userdetails;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zdp.domain.Role;
import com.zdp.domain.User;
import com.zdp.domain.UserRole;
import com.zdp.mapper.RoleMapper;
import com.zdp.mapper.UserRoleMapper;
import com.zdp.mapper.UsersMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author sesshomaru
 * @date 2021/7/6
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UsersMapper usersMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    //.httpBasic(Customizer.withDefaults()) 备注:可以配置username的参数名， 开启后这个用于认证用户账号密码以及获取用户权限
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("configure引用UserDetailsServiceImpl重写的认证=============================>>>>>>>>>>");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = usersMapper.selectOne(queryWrapper);
        if (!Optional.ofNullable(user).isPresent()) {
            throw new UsernameNotFoundException("未找到用户名");
        }
        // 添加权限
        Set<Role> roles = new HashSet<>();
        // 查询当前用户具备的权限
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", user.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
        for (UserRole userRole : userRoles) {
            Role role = roleMapper.selectById(userRole.getRoleId());
            roles.add(role);
        }
        user.setAuthorities(roles);
        log.info("configure引用UserDetailsServiceImpl重写的认证<<<<<<<<<<=============================");
        return user;
    }
}
